package com.typingtutor.ui.compose;

import com.typingtutor.dto.FieldKeyInfoDAO;
import com.typingtutor.dto.FieldMappingDAO;
import com.typingtutor.dto.FolderDAO;
import com.typingtutor.dto.RandomRuleDAO;
import com.typingtutor.model.FieldKeyInfo;
import com.typingtutor.model.Folder;
import com.typingtutor.model.RandomRule;
import com.typingtutor.util.OperatorUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * RadioButtonFieldPanel 表示单个包含单选框的输入项组件，
 * 包含一个 JRadioButton、一个 JLabel（显示名称）及一个删除按钮，
 * 同时支持右键删除。
 */
public class RadioButtonFieldPanel extends JPanel {
    private JRadioButton radioButton;
    private ButtonGroup radioButtonGroup;
    private JPanel contentPanel;
    private JLabel uuidLabel;
    private ComboBoxFieldPanel randomRangeComboBoxPanel;
    private ComboBoxFieldPanel operatorComboBoxPanel;
    private ComboBoxFieldPanel matchFieldComboBoxPanel;

    public RadioButtonFieldPanel(DefaultMutableTreeNode node, String uuid, JPanel parent, JPanel contentPanel, ButtonGroup radioButtonGroup) {
        setLayout(new GridBagLayout());
        this.contentPanel = contentPanel;
        this.radioButtonGroup = radioButtonGroup;

        // 创建并隐藏 uuidLabel
        uuidLabel = new JLabel(uuid);
        uuidLabel.setVisible(false);

        // 初始化约束参数
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.anchor = GridBagConstraints.LINE_START; // 默认左对齐
        gbc.insets = new Insets(2, 2, 2, 2);        // 缩小全局间距

        // ---------------------- 单选按钮 ----------------------
        radioButton = new JRadioButton();
        radioButtonGroup.add(radioButton);
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.weightx = 0;  // 禁止水平扩展
        add(radioButton, gbc);
        radioButton.addActionListener(e ->
                RandomRuleDAO.getInstance().enableRandomRule(getRadioButtonSelectedValue()));

        AtomicInteger row = new AtomicInteger(1);
        if (parent instanceof CollapsibleListPanel) {
            // 定义子面板共用约束
            GridBagConstraints subGbc = new GridBagConstraints();
            subGbc.gridx = 0;
            subGbc.anchor = GridBagConstraints.LINE_START;
            subGbc.insets = new Insets(0, 20, 0, 0); // 左侧缩进 20px 实现层级效果
            subGbc.fill = GridBagConstraints.HORIZONTAL;
            subGbc.weightx = 1.0; // 允许子面板水平扩展
            String[] randomItem = FolderDAO.getInstance().findSubFolderById(((Folder) node).getId())
                    .stream().map(Folder::getName).toArray(String[]::new);
            if (ArrayUtils.isEmpty(randomItem)) {
                // 防止报错
                randomItem = new String[]{""};
            }
            randomRangeComboBoxPanel = new ComboBoxFieldPanel(uuid, contentPanel, "随机范围", randomItem, false);
            subGbc.gridy = row.getAndIncrement();
            add(randomRangeComboBoxPanel, subGbc);

            operatorComboBoxPanel = new ComboBoxFieldPanel(uuid, contentPanel, "操作符", OperatorUtils.getAllOperators(), false);
            subGbc.gridy = row.getAndIncrement();
            add(operatorComboBoxPanel, subGbc);

            matchFieldComboBoxPanel = new ComboBoxFieldPanel(uuid, contentPanel, "匹配字段",
                    FieldKeyInfoDAO.getInstance().findByFolderRandomRulesId(uuid).stream()
                            .map(FieldKeyInfo::getFieldKey).toArray(String[]::new)
                    , false);
            subGbc.gridy = row.getAndIncrement();
            add(matchFieldComboBoxPanel, subGbc);

            FieldKeyInfoDAO.getInstance().findByFolderRandomRulesId(uuid).forEach(item -> {
                JCheckBox switchCheckBox = new JCheckBox(item.getFieldKey());
                switchCheckBox.setSelected(item.isDisplay());
                // 添加事件监听器
                switchCheckBox.addActionListener(e ->
                        FieldMappingDAO.getInstance().updateTypingUIDisplay(switchCheckBox.getText()
                , switchCheckBox.isSelected()));
                subGbc.gridy = row.getAndIncrement();
                add(switchCheckBox, subGbc);
            });
            RandomRuleDAO.getInstance().findById(uuid).forEach(item -> {
                randomRangeComboBoxPanel.setSelectValue(item.getRandomRange());
                operatorComboBoxPanel.setSelectValue(item.getOperatorStr());
                matchFieldComboBoxPanel.setSelectValue(item.getMathField());
            });
        }

        JButton deleteButton = new JButton("删除");
        deleteButton.addActionListener(e -> removeThis());
        gbc.gridx = 0;
        gbc.gridy = row.get();
        gbc.anchor = GridBagConstraints.LINE_END; // 右对齐
        gbc.weightx = 1.0;  // 允许按钮占用剩余空间向右对齐
        gbc.insets = new Insets(2, 2, 2, 2);      // 重置按钮间距
        add(deleteButton, gbc);

        // 右键删除
        addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                if (e.isPopupTrigger()) {
                    removeThis();
                }
            }

            @Override
            public void mouseReleased(MouseEvent e) {
                if (e.isPopupTrigger()) {
                    removeThis();
                }
            }
        });
    }

    public RadioButtonFieldPanel(DefaultMutableTreeNode node, String uuid, JPanel parent, JPanel contentPanel, ButtonGroup radioButtonGroup,
                                 boolean isEnabled) {
        this(node, uuid, parent, contentPanel, radioButtonGroup);
        setRadioButtonSelected(isEnabled);
    }
    private void removeThis() {
        RandomRuleDAO.getInstance().deleteById(uuidLabel.getText());
        // 这里可以添加移除当前面板的逻辑
        // 例如从父容器中移除当前面板
        Component parent = getParent();
        if (parent instanceof Container) {
            ((Container) parent).remove(this);
            ((Container) parent).revalidate();
            ((Container) parent).repaint();
        }
    }

    // 获取 uuid 的方法
    public String getUuid() {
        return uuidLabel.getText();
    }

    public void setUuidLabel(String text) {
        uuidLabel.setText(text);
    }

    // 获取随机范围下拉框的值
    public String getRandomRangeValue() {
        return randomRangeComboBoxPanel != null ? randomRangeComboBoxPanel.getSelectedValue() : null;
    }

    public void setRandomRangeValue(String text) {
        randomRangeComboBoxPanel.setSelectValue(text);
    }

    // 获取操作符下拉框的值
    public String getOperatorValue() {
        return operatorComboBoxPanel != null ? operatorComboBoxPanel.getSelectedValue() : null;
    }

    public void setOperatorValue(String text) {
        operatorComboBoxPanel.setSelectValue(text);
    }

    // 获取匹配字段下拉框的值
    public String getMatchFieldValue() {
        return matchFieldComboBoxPanel != null ? matchFieldComboBoxPanel.getSelectedValue() : null;
    }

    public void setMatchFieldValue(String text) {
        matchFieldComboBoxPanel.setSelectValue(text);
    }
    public void setRadioButtonSelected(boolean selected) {
        radioButton.setSelected(selected);
    }
    public boolean isRadioButtonSelected() {
        return radioButton.isSelected();
    }
    public String getRadioButtonSelectedValue() {
        return radioButton.isSelected() ? uuidLabel.getText() : StringUtils.EMPTY;
    }
}